package cn.bluethink.eguan.core.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;

import cn.bluethink.eguan.core.entity.EgGoodsEntity;
import cn.bluethink.eguan.core.entity.EgGoodsHistoryEntity;
import cn.bluethink.eguan.core.entity.GoodsHistoryEntity;
import cn.bluethink.eguan.core.mapper.EgGoodsHistoryMapper;
import cn.bluethink.eguan.core.mapper.EgGoodsMapper;
import cn.bluethink.eguan.filter.GoodsFilter;
import cn.bluethink.eguan.model.core.EgConfigInfo;
import cn.bluethink.eguan.model.core.EgGoods;
import cn.bluethink.eguan.model.core.EgGoodsStatus;
import cn.bluethink.eguan.model.core.EgOType;
import cn.bluethink.eguan.model.core.EgUser;
import cn.bluethink.eguan.result.PageInfo;
import cn.bluethink.eguan.utils.DateUtil;
import cn.bluethink.eguan.utils.IdMakerUtils;

/**
 * 商品历史业务层
 * 
 * @author 苏州中科蓝迪公司所有(c)2016-2021
 * @version 0.3.0
 * @brief 驿馆+产品
 * @note 修订历史： 1.wanglei于2018/11/28设计并构建初始版本v0.3.0
 */

@Service
public class EgGoodsHistoryService {

    @Autowired
    private EgGoodsMapper goodsMapper;

    @Autowired
    private EgGoodsHistoryMapper goodsHistoryMapper;

    @Autowired
    private EgConfigInfo configInfo;

    private IdMakerUtils idMakerUtil = new IdMakerUtils();

    /**
     * 创建历史商品（将商品变为历史商品）
     * 
     * @param goods
     * @return
     * @throws Exception
     */
    @Transactional(transactionManager = "eguanTransactionManager", rollbackFor = Exception.class)
    public EgGoods create(EgGoods goods) throws Exception {
        // 获取商品的主键ID
        Long gdid = goods.getId();
        EgGoodsEntity entity = goodsMapper.selectByPrimaryKey(gdid);
        // 创建历史商品实体
        EgGoodsHistoryEntity historyEntity = new EgGoodsHistoryEntity(goods, entity.getUid());
        historyEntity.setId(idMakerUtil.nextId());
        int insertCount = goodsHistoryMapper.insertSelective(historyEntity);
        return insertCount > 0 ? historyEntity.createEgGoods() : null;
    }

    /**
     * 批量插入同一个包裹中的历史商品
     * 
     * @param goodsList
     * @return
     * @throws Exception
     */
    @Transactional(transactionManager = "eguanTransactionManager", rollbackFor = Exception.class)
    public Boolean createList(List<EgGoods> goodsList) throws Exception {
        // 同一个包裹中的创建者相同
        EgGoodsEntity entity = goodsMapper.selectByPrimaryKey(goodsList.get(0).getId());
        List<EgGoodsHistoryEntity> entites = new ArrayList<>();
        for (EgGoods goods : goodsList) {
            EgGoodsHistoryEntity historyEntity = new EgGoodsHistoryEntity(goods, entity.getUid());
            historyEntity.setId(idMakerUtil.nextId());
            entites.add(historyEntity);
        }
        // 批量插入
        if (goodsHistoryMapper.insertList(entites) == 0) {
            return false;
        }
        return true;
    }

    /**
     * 更新历史商品状态（完成派发）
     * 
     * @param id
     * @return
     * @throws Exception
     */
    @Transactional(transactionManager = "eguanTransactionManager", rollbackFor = Exception.class)
    public Boolean update(Long id) throws Exception {
        EgGoodsHistoryEntity entity = new EgGoodsHistoryEntity();
        entity.setId(id);
        entity.setStatus(EgGoodsStatus.STATUS_FINISH);
        entity.setUtime(new Date());
        int insertCount = goodsHistoryMapper.updateByPrimaryKeySelective(entity);
        return insertCount > 0 ? true : false;
    }

    /**
     * 根据主键获取兑换商品的详情
     * 
     * @param id
     * @return
     * @throws Exception
     */
    public EgGoods detail(Long id) throws Exception {
        EgGoodsHistoryEntity entity = goodsHistoryMapper.selectByPrimaryKey(id);
        return entity != null ? entity.createEgGoods() : null;
    }

    /**
     * 过滤查询兑换商品列表。
     * 
     * @param filter
     * @param user
     * @return
     * @throws Exception
     */
    public PageInfo<EgGoods> history(GoodsFilter filter, EgUser user) throws Exception {
        Integer pageNum = filter.getPageNum() == null ? 1 : filter.getPageNum();
        Integer pageSize = filter.getPageSize() == null ? 50 : filter.getPageSize();
        // 构造查询条件
        String whereSql = buildQuerySql(filter, user);
        // 返回结果
        List<EgGoods> result = new ArrayList<>();
        List<GoodsHistoryEntity> entities = new ArrayList<>();
        // 判断whereSql不为空，根据条件查询
        if (whereSql != null && !"".equals(whereSql)) {
            // 分页
            PageHelper.startPage(pageNum, pageSize);
            entities = goodsHistoryMapper.selectGoodsHistoryByCondition(whereSql);
        }
        PageInfo<GoodsHistoryEntity> oldPageInfo = new PageInfo<>(entities);
        if (entities != null && entities.size() > 0) {
            result = entities.stream().map(g -> g.createEgGoods()).collect(Collectors.toList());
        }
        return new PageInfo<>(result, oldPageInfo);
    }

    /**
     * 构建query查询条件
     * 
     * @param filter
     * @return
     * @throws Exception
     */
    private String buildQuerySql(GoodsFilter filter, EgUser user) throws Exception {
        String whereSql = "";
        List<String> whereSqlList = new ArrayList<>();
        // 获取用户位置对象类型ID，以及用户位置对象ID，
        Integer otype = user.getPos().getType().getOtid();
        Long oid = user.getPos().getId();
        // 兑换商品的排序(默认为false按时间的降序排序)
        Boolean descOrAsc = filter.getDescOrAsc();
        // 兑换商品的状态
        Integer status = filter.getStatus();
        // 是否查看我兑换的商品
        Boolean bmine = filter.getBmine() == null ? false : filter.getBmine();
        // 按时间区间过滤的起止时间
        Date beginTime = filter.getBeginTime();
        // 按时间区间过滤的结束时间
        Date endTime = filter.getEndTime();
        // 商品的名称模糊查询
        String name = filter.getName();

        whereSqlList.add(" 1 = 1 ");
        if (bmine) {
            // 查询当前用户从所有神秘商人包裹中被兑换的商品列表
            whereSqlList.add(" GH.owner_otype = " + EgOType.USER);
            whereSqlList.add(" GH.owner_oid = " + user.getId());
            // 时间区间段查询
            if (beginTime != null && endTime != null) {
                whereSqlList.add(" GH.ctime between '" + DateUtil.formatDate(DateUtil.dateTime(beginTime, 0, 0, 0), "时分秒")
                        + "' and '" + DateUtil.formatDate(DateUtil.dateTime(endTime, 23, 59, 59), "时分秒") + "'");
            }
            // 商品名称模糊查询
            if (name != null && !"".equals(name)) {
                whereSqlList.add(" GH.name like '%" + name + "%'");
            }
        } else {
            // 如果用户在门派中，查询在门派中创建的神秘商人
            if (otype.equals(EgOType.FACTION)) {
                whereSqlList.add(" T.acount IN (SELECT acount FROM eg_faction WHERE fid = " + oid + ")");
            }
            // 如果用户在江湖中，查询在江湖中创建的神秘商人
            if (otype.equals(EgOType.JIANGHU)) {
                whereSqlList.add(" T.acount = " + configInfo.getAcountId());
            }
            // 查询所有神秘商人包裹中被兑换的商品列表(去除商品所有者是神秘商人的情况)
            whereSqlList.add(" GH.owner_otype != " + EgOType.TRADER);
        }
        // 根据兑换商品的状态筛选(包括兑换管理、我的兑换记录)
        if (status != null) {
            whereSqlList.add(" GH.status = " + status);
        }
        // 设置查询条件AND连接符
        if (whereSqlList.size() > 0) {
            whereSql += String.join(" AND ", whereSqlList);
        }
        if (descOrAsc != null && descOrAsc) {
            // 按照创建时间的正序排序筛选
            whereSql += " ORDER BY GH.ctime ";
        } else if (descOrAsc != null && !descOrAsc) {
            // 按照创建时间的倒序排序筛选
            whereSql += " ORDER BY GH.ctime DESC ";
        } else {
            // 默认按照派发状态（未派发在先），再按照创建时间降序排序(包括兑换管理、我的兑换记录)
            whereSql += " ORDER BY GH.status , GH.ctime DESC ";
        }
        return whereSql;
    }
}
